<template>
  <div>
    <QueryForm v-model="filters" :query-form-config="queryFormConfig" @clear="clear" @handleQuery="getDataList">
      <template v-if="meta.indexOf('CommoditySalesExport') > -1" #btns>
        <el-button v-preventReClick type="primary" @click="exportExcel">{{ $t('message.daochu') }}</el-button>
      </template>
    </QueryForm>
    <el-table ref="tableRef" v-loading="listLoading" :data="list" element-loading-text="Loading" border show-summary :summary-method="getSummaries" fit :header-row-class-name="'table-header'" class="doumee-table">
      <el-table-column prop="goodsName" align="center" :label="$t('message.spmc')" show-overflow-tooltip min-width="120" />
      <el-table-column prop="salePrice" align="center" :label="$t('message.xszr')" min-width="100" show-overflow-tooltip />
      <el-table-column prop="saleNum" align="center" :label="$t('message.xssl')" min-width="100" show-overflow-tooltip />
      <el-table-column prop="tkPrice" align="center" :label="$t('message.tkze')" min-width="100" show-overflow-tooltip />
      <el-table-column prop="tkNum" align="center" :label="$t('message.tksl')" min-width="100" show-overflow-tooltip />
      <!-- <el-table-column
        prop="stock"
        align="center"
        :label="$t('message.kucun')"
        min-width="100"
        show-overflow-tooltip
      /> -->
      <el-table-column align="center" min-width="100" show-overflow-tooltip prop="subtotalMoney">
        <template slot="header">
          <el-tooltip effect="dark" placement="top" :content="$t('message.xjdxsjtk')">
            <div class="df_ac" style="justify-content: center">
              <span>{{ $t('message.xiaoji') }}</span>
              <img style="width: 15px; margin-right: 2px" src="@/assets/icon/question.png" alt="">
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import * as XLSX from 'xlsx/xlsx.mjs'
import XLSX_STYLE from 'xlsx-style'
import { saveAs } from 'file-saver'
import dayjs from 'dayjs'
import { parseTime } from '@/utils/index'
import { goodsStatistics } from '@/api'
import { queryFormConfig } from './config'
export default {
  data () {
    return {
      queryFormConfig,
      showQk: false,
      venueList: [],
      list: [],
      mergeList: [],
      mergeIndexList: [],
      pagination: {
        page: 1,
        rows: 10
      },
      listLoading: false,
      total: 0,
      dateIndex: 1,
      filters: {},
      weekList: [],
      meta: [],
      goodsList: []
    }
  },
  created () {
    this.meta = this.$route.meta.buttons || []
    this.init()
  },
  methods: {
    init () {
      let time = []
      const start = new Date()
      const end = new Date()
      start.setTime(end.getTime() - 3600 * 1000 * 24 * 29)
      end.setTime(end.getTime())
      time = [dayjs(start).format('YYYY-MM-DD'), dayjs(end).format('YYYY-MM-DD')]
      this.$set(this.filters, 'time', time)
      this.getDataList()
    },
    getSummaries (param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = this.$t('message.heji')
          return
        } else {
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)

            if (index == 2 || index == 4) {
              sums[index] = sums[index]
            } else {
              sums[index] = sums[index].toFixed(2)
            }
          } else {
            sums[index] = '-'
          }
        }
      })
      //   for (var key = 1; key <= sums.length; key++) {
      //     const number = sums[key]
      //     if (!isNaN(number)) {
      //       if (key === 3 || key === 5) {
      //         sums[key] = parseFloat(number).toFixed(0)
      //         console.log(sums, '555')
      //       } else {
      //         sums[key] = parseFloat(number).toFixed(2)
      //         console.log(sums, '55566666')
      //       }
      //     }
      //   }
      return sums
    },
    clear () {
      this.filters = {
        time: this.filters.time
      }
      this.getDataList()
    },
    getDataList () {
      const param = this.filters
      if (param.time && param.time.length > 0) {
        param.startTime = param.time[0]
        param.endTime = param.time[1]
      } else {
        param.startTime = ''
        param.endTime = ''
      }
      this.listLoading = true
      param.venueId = sessionStorage.getItem('venueId')
      goodsStatistics({ param }).then(res => {
        this.listLoading = false
        if (res.errorCode !== '000000') return
        const dataList = res.recordList
        const recordList = []
        const mergeList = []
        const mergeIndexList = []
        var colnum = 0
        var idx = 0
        dataList.forEach((e) => {
          colnum += e.responseList.length
          e.responseList.forEach((s) => {
            s['venueName'] = e['venueName']
            mergeList.push(colnum)
            recordList.push(s)
            mergeIndexList.push(idx)
          })
          idx += e.responseList.length
        })
        this.list = recordList
        this.mergeList = mergeList
        this.mergeIndexList = mergeIndexList
      })
        .catch(() => { this.listLoading = false })
    },
    exportExcel () {
      const time = new Date().getTime()
      const filename = this.$t('message.spxstj') + time + '.xlsx'
      const user = this.$store.state.app.user
      const param = this.filters
      var aoa = []
      if (param.time && param.time.length > 0) {
        aoa = [
          [this.$t('message.cxqsrq') + param.time[0] + ' 00:00:00' + this.$t('message.cxzjrq') + param.time[1] + ' 23:59:59']
        ]
      }
      const workbook = XLSX.utils.book_new()
      var bottom = [
        [this.$t('message.dcsj') + parseTime(new Date())],
        [this.$t('message.dczh') + user.userName + ' -' + user.realName]
      ]
      // 创建工作簿
      var table_dom = this.$refs['tableRef'].$el
      const new_sheet = XLSX.utils.table_to_sheet(table_dom)
      const a = XLSX.utils.sheet_to_json(new_sheet, { header: 1 })
      aoa = aoa.concat(a).concat(bottom)
      const worksheet = XLSX.utils.json_to_sheet(aoa, { skipHeader: true })
      const headerStyle = {
        font: {
          name: 'Arial'
        }
      }
      const contentStyle = {
        font: {
          name: 'Arial'
        }
      }
      const headerRange = XLSX.utils.decode_range(worksheet['!ref'])
      for (let col = headerRange.s.c; col <= headerRange.e.c; col++) {
        const headerCell = XLSX.utils.encode_cell({ r: headerRange.s.r, c: col })
        if (worksheet[headerCell]) {
          worksheet[headerCell].s = headerStyle
        }
      }

      // 将内容样式应用到 worksheet 对象中的所有单元格
      const contentRange = XLSX.utils.decode_range(worksheet['!ref'])
      for (let row = contentRange.s.r + 1; row <= contentRange.e.r; row++) {
        for (let col = contentRange.s.c; col <= contentRange.e.c; col++) {
          const contentCell = XLSX.utils.encode_cell({ r: row, c: col })
          if (worksheet[contentCell]) {
            worksheet[contentCell].s = contentStyle
          }
        }
      }
      XLSX.utils.book_append_sheet(workbook, worksheet, 'sheet1')
      const wbout = XLSX_STYLE.write(workbook, { bookType: 'xlsx', type: 'binary' })
      const blob = new Blob([this.s2ab(wbout)], { type: 'application/octet-stream' })
      saveAs(blob, filename)
    },
    s2ab (s) {
      const buf = new ArrayBuffer(s.length)
      const view = new Uint8Array(buf)
      for (let i = 0; i < s.length; i++) {
        view[i] = s.charCodeAt(i) & 0xFF
      }
      return buf
    }
  }
}
</script>

